package org.systm.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.DefaultLoginPageConfigurer;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.systm.adminuser.entity.UserPermission;
import org.systm.adminuser.service.UserPermissionService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Configuration
public class SecurityConfigure {
    @Resource
    ObjectMapper objectMapper;

    @Resource
    UserPermissionService userPermissionService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    @SuppressWarnings("unchecked")
    public SecurityFilterChain httpBuild(HttpSecurity http) throws Exception {

        // 登录配置
        http.formLogin()
                .loginPage("/admin/user/login")
                .successHandler(new DefaultAuthenticationSuccessHandler(objectMapper))
                .failureHandler(new DefaultAuthenticationFailHandler(objectMapper))
                .and()
                .csrf().disable()
                .exceptionHandling()
                .accessDeniedHandler(new JsonAccessDeniedHandler(objectMapper));
//                .authenticationEntryPoint(new JsonAuthenticationEntryPoint(objectMapper));

        // 取消掉默认的登录和退出页面
        http.getConfigurer(DefaultLoginPageConfigurer.class)
                .disable();

        // 永远不开放的接口
        http.authorizeHttpRequests()
                .mvcMatchers(
                        "/admin/permission/update",
                        "/admin/permission/save",
                        "/admin/permission/del"
                )
                .denyAll();

        configurePermission(http);

        return http.build();
    }

    private void configurePermission(HttpSecurity http) throws Exception {
        Optional<List<UserPermission>> all = userPermissionService.findAll();
        if (all.isPresent()) {
            List<UserPermission> userPermissions = all.get();
            for (UserPermission userPermission : userPermissions) {
                http.authorizeHttpRequests()
                        .antMatchers(userPermission.getMethod(), userPermission.getUrl())
                        .hasAuthority(userPermission.getPer());
            }
        }
    }
}
